package com.mes.service.manu;

import com.mes.entity.User;
import com.yy.base.common.dao.Dao;
import com.yy.base.util.StringUtil;
import com.yy.base.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AbnormalReportService {

    @Autowired
    private Dao dao;

    /**
     * 获取异常原因列表
     * @return
     */
    public List<Map<String,Object>> getExceptionList() {
        StringBuffer sql = new StringBuffer();
        sql.append("select emes_exception_id,name from emes_exception");
        return dao.query(sql.toString(), new HashMap());
    }

    /**
     * 获取所有设备列表
     * @return
     */
    public List<Map<String,Object>> getDeviceList() {
        StringBuffer sql = new StringBuffer();
        sql.append("select eam_facilities_id,name from Eam_Facilities");
        return dao.query(sql.toString(), new HashMap());
    }

    /**
     * 获取人员列表
     * @return
     */
    public List<Map<String,Object>> getUserList() {
        StringBuffer sql = new StringBuffer();
        sql.append("select ad_user_id,name from ad_user");
        return dao.query(sql.toString(), new HashMap());
    }

    /**
     * 新增 异常上报记录
     * @param exception
     * @param facilites
     * @param receiver
     * @param description
     * @param user
     */
    public void addExceptionLog(String exception, String facilites, String receiver, String description, User user) {
        // 获取异常类型数据
        String sql = "select * from emes_exception where emes_exception_id = ? ";
        Map<String, Object> map = dao.queryUnique(sql, exception);

        // 获取设备数据
        String deviceSql = "select * from eam_facilities where eam_facilities_id = ? ";
        Map<String, Object> deviceMap = dao.queryUnique(deviceSql, facilites);

        //获取用户数据
        String[] receiverArr = receiver.split(",");
        StringBuffer userSql = new StringBuffer("select weixin,ad_user_id from ad_user  where ad_user_id in ( ");
        for (String userId : receiverArr) {
            userSql.append("'").append(userId).append("',");
        }
        userSql.deleteCharAt(userSql.length() - 1);
        userSql.append(")");

        List<Map<String,Object>> wxList = dao.query(userSql.toString(), new HashMap());

        //发送站内信
        if ("Y".equals(map.get("is_window").toString())) { // 站内信
            for (Map<String,Object> wx : wxList) {
                String insertSql = " insert into Emes_Message ("+
                        " emes_message_id,                  "+
                        " AD_ORG_ID,AD_CLIENT_ID, ISACTIVE,UPDATED, UPDATEDBY,CREATED,CREATEDBY, "+
                        " title,text, send_user "+
                        " ) VALUES ( SYS_GUID(), ?, ?, 'Y', now(), ?, now(), ?, ?, ?, ?)";

                List params = new ArrayList();
                params.add(user.getOrgId());
                params.add(user.getClientId());
                params.add(user.getId());
                params.add(user.getId());
                params.add("设备【" + deviceMap.get("name") + "】" + map.get("name"));
                params.add(description);
                params.add(wx.get("ad_user_id"));
                dao.executeSql(insertSql, params.toArray());
            }
        }

        if ("Y".equals(map.get("is_message").toString())) { // 短信

        }

        if ("Y".equals(map.get("is_weixin").toString())) { // 微信

            for (Map<String,Object> wx : wxList) {
                if (null != wx.get("weixin") && StringUtil.isNotEmpty(wx.get("weixin").toString())) {
                    sendWX("设备【" + deviceMap.get("name") + "】" + map.get("name"), wx.get("weixin").toString());
                }
            }

        }

        // 插入异常日志
        String insertSql = " insert into emeso_exception_log("+
                " emeso_exception_log_id,                  "+
                " AD_ORG_ID,AD_CLIENT_ID, ISACTIVE,UPDATED, UPDATEDBY,CREATED,CREATEDBY, "+
                " emes_exception_id,type, eam_facilities_id,time ,status,description,receiver "+
                " ) VALUES ( SYS_GUID(), ?, ?, 'Y', now(), ?, now(), ?, ?, ?, ?, ?, 'create', ?, ?)";

        List params = new ArrayList();
        params.add(user.getOrgId());
        params.add(user.getClientId());
        params.add(user.getId());
        params.add(user.getId());
        params.add(exception);
        params.add(map.get("type"));
        params.add(facilites);
        params.add(System.currentTimeMillis());
        params.add(description);
        params.add(receiver);

        dao.executeSql(insertSql, params.toArray());
    }

    /**
     * 发送微信通知
     * @param msg
     * @param openId
     */
    public void sendWX(String msg, String openId) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(SystemProperties.getValue("wxUrl") + "msg/SendKfMsg");
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print("msg=" + msg + "&openId=" + openId);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            System.out.println("调用微信返回==" + result);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
